﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfDragAndDrop
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private Point dragStartPoint;

        private void button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            dragStartPoint = e.GetPosition(null);
            status.Text = "New drag start position";
        }

        private static bool IsDragging(Point dragStartPoint, MouseEventArgs e)
        {
            var diff = e.GetPosition(null) - dragStartPoint;
            return
                e.LeftButton == MouseButtonState.Pressed &&
                (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                 Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance);
        }

        private void button_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (IsDragging(dragStartPoint, e))
            {
                status.Text = "Starting drag...";
                DragDrop.DoDragDrop(button, new DataObject("Button", button), DragDropEffects.Copy);
                status.Text = "Dragging done.";
                e.Handled = true;
            }
        }

        private void textBox_Dragging(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("Button"))
                e.Effects = DragDropEffects.Copy;
            else
                e.Effects = DragDropEffects.None;
            e.Handled = true;
        }

        private void textBox_Drop(object sender, DragEventArgs e)
        {
            var button = (Button)e.Data.GetData("Button");
            textBox.Text = string.Format("[{0}]", button.Content.ToString());
            e.Handled = true;
        }
    }
}
